package LocalStorage

import (
	"KumquatDrivesServices/utils"
	"github.com/sirupsen/logrus"
	ffmpeg_go "github.com/u2takey/ffmpeg-go"
	"os"
	"path/filepath"
	"time"
)

func (LocalEngine) CutFileForVideo(srcPath string) error {
	outPath := filepath.Join(filepath.Dir(srcPath), utils.GetBaseNameWithoutExt(srcPath))
	tempTsPath := filepath.Join(outPath, "temp.ts")
	if err := utils.CreatePath(tempTsPath); err != nil {
		return err
	}
	if err := ffmpeg_go.Input(srcPath).Output(tempTsPath, ffmpeg_go.KwArgs{
		"format": "mpegts",
		"vcodec": "copy",
		"acodec": "copy",
	}).Run(); err != nil {
		return err
	}
	if err := ffmpeg_go.Input(tempTsPath).Output(filepath.Join(outPath, "index.m3u8"), ffmpeg_go.KwArgs{
		"format":               "hls",
		"vcodec":               "copy",
		"acodec":               "copy",
		"map":                  "0",
		"hls_time":             time.Duration(30) * time.Second,
		"hls_list_size":        0, // 0 表示不限制播放列表中的段数
		"hls_segment_filename": filepath.Join(outPath, "%03d.ts"),
		"hls_flags":            "delete_segments", // 删除不再需要的旧片段
	}).Run(); err != nil {
		return err
	}
	if err := os.Remove(tempTsPath); err != nil {
		logrus.Errorf("failed to remove temp ts file %s", tempTsPath)
	}
	return nil
}
